﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace FBA.Client.Utils
{
    public partial class ElectronicBalanceSerialPort
    {
        private static SerialPort _port;
        public static Action<decimal> DataReceived { get; set; }


        #region 串口配置信息
        public static string PortName { get; private set; }
        public static int BaudRate { get; private set; }
        public static int DataBits { get; private set; }
        #endregion

        public static void Init()
        {
            try
            {
                string portName = ConfigurationManager.AppSettings["EB.PortName"];
                string baudRate = ConfigurationManager.AppSettings["EB.BaudRate"];
                string dataBits = ConfigurationManager.AppSettings["EB.DataBits"];
                if (string.IsNullOrEmpty(portName) || string.IsNullOrEmpty(baudRate) || string.IsNullOrEmpty(dataBits))
                {
                    return;
                }
                Init(portName, int.Parse(baudRate), int.Parse(dataBits));
            }
            catch
            {
                MessageBox.Show("Load electronic balance serial port configuration failed");
                return;
            }
        }

        public static void Init(string portName, int baudRate, int dataBits)
        {
            if (_port != null && _port.IsOpen)
            {
                try
                {
                    _port.Close();
                    _port.Dispose();
                }
                catch
                {
                }
            }

            PortName = portName;
            BaudRate = baudRate;
            DataBits = dataBits;

            try
            {
                //初始化串口
                _port = new SerialPort(PortName, BaudRate, Parity.None, DataBits);
                //事件处理
                _port.DataReceived += port_DataReceived;
                //打开串口
                _port.Open();
            }
            catch
            {
                MessageBox.Show("Open serial port " + PortName + " failed");
                return;
            }
        }

        public static void SaveAndInit(string portName, int? baudRate, int? dataBits)
        {
            Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            cfa.AppSettings.Settings["EB.PortName"].Value = portName;
            cfa.AppSettings.Settings["EB.BaudRate"].Value = "" + baudRate;
            cfa.AppSettings.Settings["EB.DataBits"].Value = "" + dataBits;
            cfa.Save();
            ConfigurationManager.RefreshSection("appSettings");
            Init();
        }

        static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort sp = (SerialPort)sender;
                string inData = sp.ReadLine();
                string sign = inData.Substring(0, 1);
                string weight = inData.Substring(1, 7);
                string unit = inData.Substring(8).Trim();

                decimal w = 0;
                if (decimal.TryParse(weight, out w))
                {
                    if (sign.Equals("-"))
                    {
                        w = 0 - w;
                    }

                    if (unit.Equals("lb"))
                    {
                        w = decimal.Round(w * new decimal(0.4535924), 3);
                    }

                    if (DataReceived != null)
                    {
                        DataReceived.Invoke(w);
                    }

                }
            }
            catch (Exception)
            {
            }
        }
    }
}
